import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/AppRouter.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/pages/circle/CircleListPage.dart';
import 'package:huajianshe_app/pages/circle/MyCirclesWidget.dart';
import 'package:huajianshe_app/pages/circle/RecentCircleItem.dart';
import 'package:huajianshe_app/pages/circle/RecommendationCircleItem.dart';
import 'package:huajianshe_app/pages/circle/model/CircleHomeResp.dart';
import 'package:huajianshe_app/pages/search/SearchPage.dart';
import 'package:huajianshe_app/widget/AutoGridWidgetV2.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/RoundedUnderlineTabIndicator.dart';
import 'package:huajianshe_app/widget/SimpleScrollView.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/appbar/CircleSearchAppBar.dart';

import 'CircleDetailPage.dart';


//圈子主页
class CirclePage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _CirclePageState();
  }

}

class _CirclePageState extends BaseState<CirclePage> with SingleTickerProviderStateMixin {

  CircleHomeResp? resp;
  late TabController tabController;
  late PageController pageController;
  double headerHeight = 0;

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 2, vsync: this);
    pageController = PageController(initialPage: 0);
    load();
  }

  load() {
    sendReq(Api.circleHome(), CircleHomeResp(), data: {}, doNotShowProgressBar: false);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is CircleHomeResp) {
      if (path.contains('getCirclePageChange')) {//换一换
        print('change');
        resp?.data?.hot = t.data?.hot;
        resp?.data?.interested = t.data?.interested;
      } else {//首页
        print('home');
        resp = t;
      }
      setState(() => null);
    }
  }

  @override
  Widget build(BuildContext context) {
    headerHeight = 48;
    Widget history = buildHistory();
    Widget recent = buildRecent();
    Widget recommendation = buildRecommendation();
    Widget free = buildFree();
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CircleSearchAppBar(SearchType.circle),
      body: NestedScrollView(
        body: TabBarView(controller: tabController, children: [
          CircleListPage(type: 1,),
          CircleListPage(type: 2,)
        ]),
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
                backgroundColor: Colors.white,
                automaticallyImplyLeading: false,
                pinned: true,
                floating: true,
                expandedHeight: headerHeight,
                flexibleSpace: FlexibleSpaceBar(
                  collapseMode: CollapseMode.pin,
                  background: Container( //头部整个背景颜色
                    height: double.infinity,
                    color: Colors.white,
                    child: Column(
                      children: <Widget>[
                        history,
                        recent,
                        recommendation,
                        free
                      ],
                    ),
                  ),
                ),
                bottom: PreferredSize(preferredSize: Size.fromHeight(48),
                    child: ColoredBox(color: Colors.transparent, child: Align(alignment: Alignment.centerLeft,
                      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                        Padding(padding: EdgeInsets.symmetric(horizontal: 13, vertical: 6), child: TabBar(
                            onTap: (index) { pageController.jumpToPage(index); },
                            labelPadding: EdgeInsets.only(left: 6, right: 26, bottom: 3),
                            indicatorWeight: 1,
                            indicatorSize: TabBarIndicatorSize.label,
                            indicator: RoundedUnderlineTabIndicator(
                              insets: EdgeInsets.only(left: -15, top: 0, bottom: -5),
                              borderSide: BorderSide(width: 1, color: C.primary),
                            ),
                            isScrollable: true,
                            controller: tabController,
                            labelColor: C.gray333,
                            unselectedLabelColor: C.gray999,
                            labelStyle: TS(18, C.gray333, fontWeight: FontWeight.bold),
                            unselectedLabelStyle: TS(14, C.gray999),
                            tabs: [Text('我加入的'), Text('我创建的')]
                        )),
                        D()
                      ]),
                    ))
                )
            )
          ];
        },
      ),
        floatingActionButton: Padding(padding: EdgeInsets.only(bottom: 60),child:FloatingActionButton(
          backgroundColor: Colors.transparent,
          // child: LoadImage('send_moment'),
          child: Container(width: 52, height: 52, decoration: BoxDecoration(shape: BoxShape.circle, gradient:
          LinearGradient(colors: [Color(0xFFFE2E2E), Color(0xFFF78C58)], begin: Alignment.topCenter, end: Alignment.bottomCenter),
          ), child: Icon(Icons.add),),
          onPressed: () { AppNavigator.push(context, RouteName.CIRCLE_CREATE); },
        ))
    );
  }

  Widget buildHistory() {

    //最上面的历史
    if (resp?.data?.history?.isNotEmpty == true) {
      List<Widget> widgets = [];
      for (int i = 0; i < resp!.data!.history!.length; i++) {
        if (i > 0) {
          widgets.add(W(6));
        }
        BaseHomeCircleInfo info = resp!.data!.history![i];
        widgets.add(SmartButton(text: info.title ?? '', textColor: C.gray0D0E15, fontSize: 12, backgroundColor: C.grayF6, borderColor: Colors.transparent,
          padding: EdgeInsets.symmetric(vertical: 4, horizontal: 11), height: 26, width: null, radius: 14, onPressed: () => circleDetail(info.id),));
      }
      headerHeight += 52;
      return SizedBox(width: double.infinity, height: 50,
        child: Padding(padding: EdgeInsets.only(top: 10),
          child: SingleChildScrollView(scrollDirection: Axis.horizontal,
            child: Row(children: [
              W(13),
              ...widgets,
              W(13)
            ])
          )
        )
      );
    }
    return H(0);
  }

  Widget buildRecent() {//最近
    List<RecentHomeCircleInfo>? recent = resp?.data?.recent;
    print('${recent}');
    if (recent?.isNotEmpty == true) {
      Widget container = Container( //44
        height: 24,
        padding: EdgeInsets.only(left: 15, right: 15, top: 6),
        child: GestureDetector(onTap: () { recentList(); },
            child: Row(children: [
              Text('最近经常访问的圈子', style: TS(13, C.gray999)),
              Spacer(),
              LoadImage('ic_gray_right_arrow'),
              W(15)
            ])
        )
      );
      List<Widget> cards = [];
      for (int i = 0; i < recent!.length; i++) {
        if (i > 0) {
          cards.add(W(0));
        }
        cards.add(GestureDetector(onTap: () =>  circleDetail(recent[i].id), child: RecentCircleItem(recent[i]))); //height 200
      }
      Widget cards_ = SingleChildScrollView(scrollDirection: Axis.horizontal,
          child: Row(children: [
            W(10),
            ...cards,
            W(15)
          ])
      );
      headerHeight += 10 + 24 + 200 + 2;
      return Column(mainAxisSize: MainAxisSize.min, children: [D(), H(10), container, cards_],);
    }
    return H(0);
  }

  recentList() {
    // circleDetail(1);
    AppNavigator.push(context, RouteName.CIRCLE_MORE, arguments: {'type': 2, 'title': '最近访问'});
  }

  Widget buildRecommendation() {
    if (resp?.data?.hot?.isNotEmpty == true || resp?.data?.interested?.isNotEmpty == true) {
      Widget title = Container(
          height: 42,
          padding: EdgeInsets.only(left: 15, right: 15, top: 0),
          child: GestureDetector(onTap: () { recentList(); },
              child: Row(children: [

                Text('每日圈子推荐', style: TS(18, C.gray333, fontWeight: FontWeight.bold),),
                Spacer(),
                SmartButton(text: '换一换', fontSize: 14, textColor: C.gray999, backgroundColor: Colors.transparent, onPressed: changeRecommendation,
                  width: 65, height: 20, drawableRight: LoadImage('ic_gray_right_arrow'), drawablePadding: 5, borderColor: Colors.transparent,
                ),

              ])
          )
      );
      Widget content = Row(children: [
        W(13),
        Flexible(child: RecommendationCircleItem(
            resp?.data?.hot, '热门圈子', 'bg_hot_circle', this.moreHot)),
        W(11),
        Flexible(child: RecommendationCircleItem(
            resp?.data?.interested, '可能感兴趣', 'bg_interested_circle', this.moreInteresting)),
        W(13)
      ]);
      headerHeight += 42 + 222;
      return Column(mainAxisSize: MainAxisSize.min, children: [title, content]);
    }
    return H(0);
  }

  moreHot() { // 热门圈子列表
    AppNavigator.push(context, RouteName.CIRCLE_MORE, arguments: {'type': 3, 'title': '热门推荐'});
  }

  moreInteresting() { // 感兴趣列表
    AppNavigator.push(context, RouteName.CIRCLE_MORE, arguments: {'type': 4, 'title': '感兴趣'});
  }

  Widget buildFree() {
    if (resp?.data?.free?.isNotEmpty == true) {
      Widget title = Container(
          height: 50,
          padding: EdgeInsets.only(left: 15, right: 15, top: 8),
          child: GestureDetector(onTap: () { recentList(); },
              child: Row(children: [
                Text('免费洞察圈子', style: TS(18, C.gray333, fontWeight: FontWeight.bold)),
                Spacer(),
                SmartButton(text: '更多', fontSize: 14, textColor: C.gray999, backgroundColor: Colors.transparent,
                   height: 20, drawableRight: LoadImage('ic_gray_right_arrow'), drawablePadding: 5, borderColor: Colors.transparent,
                ),
              ])
          )
      );
      Widget content = Padding(padding: EdgeInsets.symmetric(horizontal: 13),
          child: AutoGridWidgetV2(colNum: 3, padding: 6, height: 65, widgets: [
            ...resp!.data!.free!.map((e) {
              return GestureDetector(onTap: () => circleDetail(e.id), child: RoundedCornerWidget(
                child: ClipRRect(borderRadius: BorderRadius.circular(3), child: ColoredBox(color: Color.fromRGBO(0x24, 0x21, 0x21, 0.55),
                  child: Padding(padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                      child: Column(children: [
                        Text(e.title ?? '', style: TS(12, C.grayDDD)),
                        Spacer(),
                        Text('${e.num}人', style: TS(10, Color.fromRGBO(0xff, 0xdd, 0x00, 0.6)))
                      ])
                  ),
                )),
                radius: 6, height: 65, borderWidth: 0, image: LoadImage.getImageProvider(e.cover ?? ''),));
            }).toList()
          ])
      );
      headerHeight += 50 + 65;
      return Column(mainAxisSize: MainAxisSize.min, children: [title, content]);
    }
    return H(0);
  }

  changeRecommendation() { //换一换
    List hot = resp?.data?.hot?.map((e) => e.id).toList() ?? [];
    List interested = resp?.data?.interested?.map((e) => e.id).toList() ?? [];
    var data = {
      'recommend_ids': hot.join(','),
      'interest_ids': interested.join(',')
    };
    print('$data');
    sendReq(Api.circleChange(), CircleHomeResp(), data: data);
  }

  circleDetail(int? circleId) {
    print('circleId: ${circleId}');
    AppNavigator.push(context, RouteName.CIRCLE_DETAIL, arguments: {'circleDetailType': CircleDetailType.inner, 'circleId': circleId});
  }
}